using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraEditors.Controls;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Collections.Specialized;
using WeChatFileManagementWinApp;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.Utils;

namespace WeChatFileManagementWinApp
{
    /// <summary>
    /// 主窗体类，负责用户界面的显示和交互
    /// </summary>
    public partial class MasterForm : Form
    {
        // P/Invoke for ShellExecute
        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);

        // P/Invoke for SHObjectProperties
        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern bool SHObjectProperties(IntPtr hwnd, uint shopObjectType, string pszObjectName, string pszPropertyPage);

        // SHObjectProperties flags
        private const uint SHOP_FILEPATH = 0x00000002; // object name is a file path

        private const int SW_SHOW = 5;

        private static WeChatFileSearcher _searcher;
        private readonly Dictionary<string, Color> _extensionColors;
        private readonly ContextMenuStrip _contextMenuStrip;
        private readonly SettingsManager _settingsManager;
        private System.Threading.Timer _searchTimer;
        private const int SEARCH_INTERVAL = 5 * 60 * 1000; // 5分钟，单位：毫秒

        // UI elements for progress are now on statusStrip1 and declared in Form1.Designer.cs
        // private System.Windows.Forms.Panel overlayPanel;
        // private System.Windows.Forms.ProgressBar searchProgressBar;
        // private System.Windows.Forms.Label progressStatusLabel;

        /// <summary>
        /// 初始化主窗体
        /// </summary>
        public MasterForm()
        {
            InitializeComponent();
            this.Text = "微信文件管理";
            toolStripStatusLabel2.Text = "";

            _settingsManager = new SettingsManager();
            _extensionColors = InitializeExtensionColors();
            _contextMenuStrip = InitializeContextMenu();

            // 初始化搜索器
            var directories = _settingsManager.LoadSearchDirectories();
            _searcher = new WeChatFileSearcher(directories);
            _searcher.ProgressChanged += Searcher_ProgressChanged;

            // 绑定 GridView 事件
            gridView1.FocusedRowChanged += GridView1_FocusedRowChanged;

            InitializeTimer();
            Initialize();
        }

        /// <summary>
        /// 初始化定时器
        /// </summary>
        private void InitializeTimer()
        {
            _searchTimer = new System.Threading.Timer(TimerCallback, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
        }

        /// <summary>
        /// 定时器回调方法
        /// </summary>
        private void TimerCallback(object state)
        {
            Task.Run(() =>
            {
                try
                {
                    // 执行搜索
                    _searcher.SearchWeChatFiles();

                    // 更新UI和保存结果
                    this.Invoke((MethodInvoker)delegate
                    {
                        try
                        {
                            _settingsManager.SaveSearchResults(_searcher.FoundFiles.ToList());
                            gridControl1.DataSource = _searcher.FoundFiles;
                            UpdateFileCounts();
                            toolStripStatusLabel1.Text = $"自动更新完成 ({DateTime.Now:HH:mm:ss})";
                        }
                        catch (Exception ex)
                        {
                            toolStripStatusLabel1.Text = $"自动更新失败: {ex.Message}";
                        }
                    });
                }
                catch (Exception ex)
                {
                    this.Invoke((MethodInvoker)delegate
                    {
                        toolStripStatusLabel1.Text = $"自动更新失败: {ex.Message}";
                    });
                }
            });
        }

        /// <summary>
        /// 启动自动搜索
        /// </summary>
        private void StartAutoSearch()
        {
            _searchTimer.Change(0, SEARCH_INTERVAL);
            toolStripStatusLabel1.Text = "自动更新已启动";
        }

        /// <summary>
        /// 停止自动搜索
        /// </summary>
        private void StopAutoSearch()
        {
            _searchTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
            toolStripStatusLabel1.Text = "自动更新已停止";
        }

        /// <summary>
        /// 窗体关闭时清理资源
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);

            // 清理定时器
            if (_searchTimer != null)
            {
                _searchTimer.Dispose();
                _searchTimer = null;
            }

            // 清理文件资源
            if (gridControl1.DataSource is List<WeChatFile> files)
            {
                foreach (var file in files)
                {
                    file.Dispose();
                }
            }
        }

        /// <summary>
        /// 初始化文件扩展名颜色映射
        /// </summary>
        private Dictionary<string, Color> InitializeExtensionColors()
        {
            return new Dictionary<string, Color>(StringComparer.OrdinalIgnoreCase)
            {
                // 文档类型
                { ".doc", Color.FromArgb(255, 240, 248, 255) },  // 浅蓝色
                { ".docx", Color.FromArgb(255, 240, 248, 255) },
                { ".txt", Color.FromArgb(255, 240, 248, 255) },
                { ".pdf", Color.FromArgb(255, 240, 248, 255) },
                
                // 图片类型
                { ".jpg", Color.FromArgb(255, 255, 240, 245) },  // 浅粉色
                { ".jpeg", Color.FromArgb(255, 255, 240, 245) },
                { ".png", Color.FromArgb(255, 255, 240, 245) },
                { ".gif", Color.FromArgb(255, 255, 240, 245) },
                { ".bmp", Color.FromArgb(255, 255, 240, 245) },
                
                // 视频类型
                { ".mp4", Color.FromArgb(255, 240, 255, 240) },  // 浅绿色
                { ".avi", Color.FromArgb(255, 240, 255, 240) },
                { ".mov", Color.FromArgb(255, 240, 255, 240) },
                { ".wmv", Color.FromArgb(255, 240, 255, 240) },
                
                // 音频类型
                { ".mp3", Color.FromArgb(255, 255, 248, 240) },  // 浅橙色
                { ".wav", Color.FromArgb(255, 255, 248, 240) },
                { ".wma", Color.FromArgb(255, 255, 248, 240) },
                
                // 压缩文件
                { ".zip", Color.FromArgb(255, 248, 240, 255) },  // 浅紫色
                { ".rar", Color.FromArgb(255, 248, 240, 255) },
                { ".7z", Color.FromArgb(255, 248, 240, 255) }
            };
        }

        /// <summary>
        /// 初始化上下文菜单
        /// </summary>
        private ContextMenuStrip InitializeContextMenu()
        {
            var menu = new ContextMenuStrip();

            // 打开文件
            var openItem = new ToolStripMenuItem("打开");
            openItem.Click += (s, e) => OpenSelectedFile();
            menu.Items.Add(openItem);

            // 打开文件所在文件夹
            var openFolderItem = new ToolStripMenuItem("打开所在文件夹");
            openFolderItem.Click += (s, e) => OpenFileLocation();
            menu.Items.Add(openFolderItem);

            // 查看属性
            var propertiesItem = new ToolStripMenuItem("属性");
            propertiesItem.Click += (s, e) => ShowFileProperties();
            menu.Items.Add(propertiesItem);

            menu.Items.Add(new ToolStripSeparator());

            // 复制文件
            var copyFileItem = new ToolStripMenuItem("复制");
            copyFileItem.Click += (s, e) => CopyFile();
            menu.Items.Add(copyFileItem);

            // 复制文件名
            var copyNameItem = new ToolStripMenuItem("复制文件名");
            copyNameItem.Click += (s, e) => CopyFileName();
            menu.Items.Add(copyNameItem);

            // 复制文件路径
            var copyPathItem = new ToolStripMenuItem("复制文件路径");
            copyPathItem.Click += (s, e) => CopyFullPath();
            menu.Items.Add(copyPathItem);

            menu.Items.Add(new ToolStripSeparator());

            // 删除文件
            var deleteItem = new ToolStripMenuItem("删除");
            deleteItem.Click += (s, e) => DeleteFile();
            menu.Items.Add(deleteItem);

            menu.Items.Add(new ToolStripSeparator());

            // 刷新
            var refreshItem = new ToolStripMenuItem("刷新");
            refreshItem.Click += (s, e) => Initialize();
            menu.Items.Add(refreshItem);

            menu.Items.Add(new ToolStripSeparator());

            // 设置搜索目录
            var settingsItem = new ToolStripMenuItem("设置搜索目录");
            settingsItem.Click += (s, e) => ShowSettingsForm();
            menu.Items.Add(settingsItem);

            // 添加自动更新菜单项
            var autoUpdateItem = new ToolStripMenuItem("自动更新");
            var startAutoUpdateItem = new ToolStripMenuItem("启动自动更新");
            var stopAutoUpdateItem = new ToolStripMenuItem("停止自动更新");

            startAutoUpdateItem.Click += (s, e) => StartAutoSearch();
            stopAutoUpdateItem.Click += (s, e) => StopAutoSearch();

            autoUpdateItem.DropDownItems.Add(startAutoUpdateItem);
            autoUpdateItem.DropDownItems.Add(stopAutoUpdateItem);
            menu.Items.Add(autoUpdateItem);

            // 将上下文菜单绑定到 GridView
            gridView1.MouseUp += GridView1_MouseUp;

            return menu;
        }

        /// <summary>
        /// 处理GridView鼠标右键点击事件
        /// </summary>
        private void GridView1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                GridHitInfo hitInfo = gridView1.CalcHitInfo(e.Location);
                if (hitInfo.InRow)
                {
                    gridView1.FocusedRowHandle = hitInfo.RowHandle;
                    _contextMenuStrip.Show(gridControl1, e.Location);
                }
            }
        }

        /// <summary>
        /// 打开选中的文件
        /// </summary>
        private void OpenSelectedFile()
        {
            var file = GetSelectedFile();
            if (file != null)
            {
                file.Open();
            }
        }

        /// <summary>
        /// 打开文件所在文件夹
        /// </summary>
        private void OpenFileLocation()
        {
            var file = GetSelectedFile();
            if (file != null)
            {
                file.OpenLocation();
            }
        }

        /// <summary>
        /// 显示文件属性
        /// </summary>
        private void ShowFileProperties()
        {
            var file = GetSelectedFile();
            if (file != null)
            {
                file.ShowProperties();
            }
        }

        /// <summary>
        /// 复制文件名
        /// </summary>
        private void CopyFileName()
        {
            var file = GetSelectedFile();
            if (file != null)
            {
                file.CopyNameToClipboard();
            }
        }

        /// <summary>
        /// 复制文件路径
        /// </summary>
        private void CopyFullPath()
        {
            var file = GetSelectedFile();
            if (file != null)
            {
                file.CopyPathToClipboard();
            }
        }

        /// <summary>
        /// 复制文件
        /// </summary>
        private void CopyFile()
        {
            var file = GetSelectedFile();
            if (file != null)
            {
                file.CopyToClipboard();
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        private void DeleteFile()
        {
            var file = GetSelectedFile();
            if (file != null && file.Delete())
            {
                // 刷新文件列表
                Initialize();
            }
        }

        /// <summary>
        /// 显示设置窗体
        /// </summary>
        private void ShowSettingsForm()
        {
            using (var settingsForm = new SettingsForm(_settingsManager))
            {
                if (settingsForm.ShowDialog() == DialogResult.OK)
                {
                    // 重新加载搜索目录并刷新
                    var directories = _settingsManager.LoadSearchDirectories();
                    _searcher = new WeChatFileSearcher(directories);
                    _searcher.ProgressChanged += Searcher_ProgressChanged;
                    Initialize();
                }
            }
        }

        /// <summary>
        /// 获取当前选中的文件
        /// </summary>
        private WeChatFile GetSelectedFile()
        {
            int rowHandle = gridView1.FocusedRowHandle;
            if (rowHandle >= 0)
            {
                return gridView1.GetRow(rowHandle) as WeChatFile;
            }
            return null;
        }

        /// <summary>
        /// 初始化窗体
        /// </summary>
        private void Initialize()
        {
            try
            {
                ShowProgress(0, "正在加载...");

                // 配置图标列
                var pictureEdit = new RepositoryItemPictureEdit();
                pictureEdit.SizeMode = PictureSizeMode.Zoom;
                pictureEdit.BorderStyle = BorderStyles.NoBorder;
                glIcom.ColumnEdit = pictureEdit;

                // 配置 GridView 样式
                gridView1.OptionsSelection.EnableAppearanceFocusedRow = true;
                gridView1.OptionsSelection.EnableAppearanceHideSelection = true;
                gridView1.FocusRectStyle = DrawFocusRectStyle.RowFocus;

                // 设置焦点行样式
                gridView1.Appearance.FocusedRow.BackColor = Color.FromArgb(230, 230, 230);
                gridView1.Appearance.FocusedRow.ForeColor = Color.Blue;
                gridView1.Appearance.FocusedRow.Font = new Font("Microsoft YaHei UI", 9F);

                // 设置隐藏选择行样式
                gridView1.Appearance.HideSelectionRow.BackColor = Color.FromArgb(240, 240, 240);
                gridView1.Appearance.HideSelectionRow.ForeColor = Color.Blue;
                gridView1.Appearance.HideSelectionRow.Font = new Font("Microsoft YaHei UI", 9F);

                // 设置焦点单元格样式
                gridView1.Appearance.FocusedCell.BackColor = Color.FromArgb(230, 230, 230);
                gridView1.Appearance.FocusedCell.ForeColor = Color.Blue;
                gridView1.Appearance.FocusedCell.Font = new Font("Microsoft YaHei UI", 9F);

                // 加载保存的搜索结果
                var savedResults = _settingsManager.LoadSearchResults();
                if (savedResults.Any())
                {
                    gridControl1.DataSource = savedResults;
                    UpdateFileCounts();
                }

                // 执行新的搜索
                ExecuteSearch();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                HideProgress("就绪");
            }
        }

        /// <summary>
        /// 执行搜索
        /// </summary>
        private void ExecuteSearch()
        {
            Task.Run(() =>
            {
                try
                {
                    _searcher.SearchWeChatFiles();
                    this.Invoke((MethodInvoker)delegate
                    {
                        try
                        {
                            _settingsManager.SaveSearchResults(_searcher.FoundFiles.ToList());
                            if (gridControl1.DataSource == null)
                                gridControl1.DataSource = _searcher.FoundFiles;
                            UpdateFileCounts();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"保存搜索结果失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    });
                }
                catch (Exception ex)
                {
                    this.Invoke((MethodInvoker)delegate
                    {
                        MessageBox.Show($"搜索失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    });
                }
            });
        }

        /// <summary>
        /// 处理搜索进度变更事件
        /// </summary>
        private void Searcher_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage >= 0)
            {
                UpdateProgressBar(e);
            }
            else
            {
                // 显示错误信息
                toolStripStatusLabel1.Text = e.UserState.ToString();
            }
        }

        /// <summary>
        /// 更新进度条
        /// </summary>
        private void UpdateProgressBar(ProgressChangedEventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<ProgressChangedEventArgs>(UpdateProgressBar), e);
                return;
            }

            ShowProgress(e.ProgressPercentage, e.UserState.ToString());
        }

        /// <summary>
        /// 更新文件计数
        /// </summary>
        private void UpdateFileCounts()
        {
            var files = _searcher.FoundFiles;
            if (files != null)
            {
                var totalCount = files.Count;
                var totalSize = files.Sum(f => f.Size);
                toolStripStatusLabel2.Text = $"共 {totalCount} 个文件，总大小: {FormatFileSize(totalSize)}，文件类型：{files.Select(n => n.Extension.ToLower()).Distinct().Count()}";
            }
        }

        /// <summary>
        /// 格式化文件大小
        /// </summary>
        private string FormatFileSize(long bytes)
        {
            string[] sizes = { "B", "KB", "MB", "GB", "TB" };
            int order = 0;
            double size = bytes;
            while (size >= 1024 && order < sizes.Length - 1)
            {
                order++;
                size /= 1024;
            }
            return $"{size:0.##} {sizes[order]}";
        }

        /// <summary>
        /// 显示进度条
        /// </summary>
        private void ShowProgress(int percentage, string statusText)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<int, string>(ShowProgress), percentage, statusText);
                return;
            }

            toolStripProgressBar1.Visible = true;
            if (percentage == 100)
            {
                toolStripProgressBar1.Visible = false;
                toolStripStatusLabel1.Visible = false;
            }
            else
            {
                toolStripProgressBar1.Visible = true;
                toolStripStatusLabel1.Visible = true;
                toolStripProgressBar1.Value = percentage;
                toolStripStatusLabel1.Text = statusText;
            }
        }

        /// <summary>
        /// 隐藏进度条
        /// </summary>
        private void HideProgress(string statusText)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(HideProgress), statusText);
                return;
            }

            toolStripProgressBar1.Visible = false;
            toolStripStatusLabel1.Text = statusText;
        }

        /// <summary>
        /// 处理焦点行改变事件
        /// </summary>
        private void GridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle >= 0)
            {
                // 更新所有行的样式
                gridView1.RefreshData();
            }
        }

        /// <summary>
        /// 处理GridView行样式事件
        /// </summary>
        private void GridView1_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                var file = gridView1.GetRow(e.RowHandle) as WeChatFile;
                if (file != null)
                {
                    // 设置行背景色
                    if (_extensionColors.TryGetValue(file.Extension, out Color color))
                    {
                        e.Appearance.BackColor = color;
                    }

                    // 如果是焦点行，设置蓝色文字
                    if (e.RowHandle == gridView1.FocusedRowHandle)
                    {
                        e.Appearance.ForeColor = Color.Blue;
                        e.Appearance.Font = new Font("Microsoft YaHei UI", 9F);
                    }

                    // 确保图标已加载
                    if (file.Icon == null)
                    {
                        file.LoadIcon();
                    }
                }
            }
        }

        /// <summary>
        /// 处理GridView行指示器绘制事件
        /// </summary>
        private void GridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
    }
}
